package com.inspector.app.ui.flight.mapsearch;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.inspector.app.R;
import com.inspector.app.ui.flight.mapsearch.poi.MapSearchPoi;
import com.mapsforge.map.EfbLatLngPoint;
import com.mapsforge.map.vtm.VtmEfbMapView;
import com.mapsforge.org.oscim.map.IDJMap;
import com.mapsforge.org.oscim.map.model.MarkerOptions;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索结果图层显示
 *
 * @author pank 2023/4/3
 */
@SuppressWarnings("ALL")
public class MapSearchLayerInstance {


    //[搜索图标]
    private Bitmap markerBitmap;
    private IDJMap dJMap;
    //[地图搜索item集合数据]
    private List<MapSearchPoi> items = new ArrayList<>();

    public List<MapSearchPoi> getItems() {
        return items;
    }

    //[初始化]
    public void setupView(Context context, IDJMap idjMap) {
        dJMap = idjMap;
        markerBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.dingwei_ditu);
    }


    //[添加item]
    public void addItem(@NotNull MapSearchPoi searchPoi) {
        if (dJMap == null) return;

        //[移除旧marker]
        MapSearchPoi mapSearchPoi = null;
        if (searchPoi.getTabType() == 0) {
            mapSearchPoi = items.stream().filter(it -> it.getTabType() == 0).findFirst().orElse(null);
        } else {
            mapSearchPoi = items.stream().filter(it -> !TextUtils.isEmpty(it.getId()) && it.getId().equals(searchPoi.getId())).findFirst().orElse(null);
        }
        if (mapSearchPoi != null && !TextUtils.isEmpty(mapSearchPoi.getMarkerId())) {
            dJMap.removeMarker(mapSearchPoi.getMarkerId());
            items.remove(mapSearchPoi);
        }

        //[添加新marker图层]
        MarkerOptions options = new MarkerOptions().title(searchPoi.getName())
                .bitmap(getBitmapByMapSearchPoi(searchPoi))
                .iconType(searchPoi.getIconType())
                .position(new EfbLatLngPoint(searchPoi.getLat(), searchPoi.getLng()));
        dJMap.addMarker(options);
        dJMap.setMapPosition(options.getPosition());

        //[更新到集合]
        searchPoi.setMarkerId(options.getId());
        items.add(searchPoi);
    }


    //[根据类型获取图片marker]
    private Bitmap getBitmapByMapSearchPoi(@NotNull MapSearchPoi searchPoi) {
        return markerBitmap;
    }


    //[清除marker图层]
    public void clearMapLayer() {
        if (dJMap == null) return;
        for (MapSearchPoi item : items) {
            if (TextUtils.isEmpty(item.getMarkerId())) continue;

            //[删除普通marker]
            dJMap.removeMarker(item.getMarkerId());
        }
        items.clear();
    }


    //[单例类]
    private static final class Holder {
        static final MapSearchLayerInstance instance = new MapSearchLayerInstance();
    }

    public static synchronized MapSearchLayerInstance getInstance() {
        return Holder.instance;
    }

}
